package com.hdcx.Minfresh.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdcx.Minfresh.url.RequstCode;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.bean.MineUserInfo;
import com.hdcx.Minfresh.bean.UserInfoBean;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.util.ShpfUtil;

import static com.hdcx.Minfresh.activity.PhotoPickerActivity.SELECT_RESULTS;
import static com.hdcx.Minfresh.activity.PhotoPickerActivity.SELECT_RESULTS_ARRAY;

/**
 * Created by Administrator on 2016/11/18.
 */

public class MineUserInfoActivity extends BaseActivity {
     TextView tv_address,tv_phone;
    ImageView img_main;
    EditText et_nick_name;
    DisplayImageOptions options;
    private String imgstring = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        initView();
        initData();
    }

    private void initView() {
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        img_main = (ImageView) findViewById(R.id.img_main);
        et_nick_name = (EditText) findViewById(R.id.et_nick_name);
        findViewById(R.id.layout_img).setOnClickListener(this);
        findViewById(R.id.bt_register).setOnClickListener(this);
        findViewById(R.id.tv_left).setOnClickListener(this);
        ((TextView)findViewById(R.id.tv_title)).setText("个人资料");
    }
    private void initData() {
          post_main();
    }
 /*   uid   //用户id*/
    private void post_main() {
        AppUtil.showLoading(this);
        UserInfoBean user =  ShpfUtil.getObject(ShpfUtil.LOGIN);
        JSONObject json = new JSONObject();
        try {
            json.put("uid",user.getUserinfo().getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.USERINFOGET)
                .content(json.toString())
                .build()
                .execute(new Callback<MineUserInfo>() {
                    @Override
                    public MineUserInfo parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, MineUserInfo.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(MineUserInfo response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            setValue(response);
                        }
                    }
                });
    }

    private void setValue(MineUserInfo response) {

        tv_address.setText(response.getUser().getAddress());
        tv_phone.setText(response.getUser().getMobile());
        et_nick_name.setText(response.getUser().getNick_name());
        ImageLoader imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder().cacheOnDisc(true).showImageOnLoading(R.drawable.img01)
                .showImageForEmptyUri(R.drawable.img01)
                .imageScaleType(ImageScaleType.EXACTLY)
                .showImageOnFail(R.drawable.img01).imageScaleType(ImageScaleType.EXACTLY)
                .displayer(new RoundedBitmapDisplayer(AppUtil.dipToPixels(40), 0))
                .bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.displayImage(response.getUser().getFace(), img_main, options);
    }


    /*参数
    uid   //用户id
    face  //头像数据
    nick_name  昵称*/
    public void post_updata() {
        UserInfoBean user =  ShpfUtil.getObject(ShpfUtil.LOGIN);
        JSONObject json = new JSONObject();
        try {
            json.put("uid",user.getUserinfo().getId());
            json.put("face",imgstring.equals("")?"":AppUtil.bitmapToBase64(AppUtil.getBitmap(imgstring)));
            json.put("nick_name",et_nick_name.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.MODPROFILE)
                .content(json.toString())
                .build()
                .execute(new Callback<UserInfoBean>() {
                    @Override
                    public UserInfoBean parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, UserInfoBean.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(UserInfoBean response) {
                        if (response.getStatus() == 1) {
                            Toast.makeText(MineUserInfoActivity.this,"修改成功！", Toast.LENGTH_SHORT).show();
                            AppUtil.isFrash=true;
                            finish();
                        }
                    }
                });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_img:
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED)
                {

                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           110);
                } else
                {
                    Intent intent1 = new Intent(this, PhotoPickerActivity.class);
                    startActivityForResult(intent1, RequstCode.GETPHOTO);
                }
                break;
            case R.id.bt_register:
                post_updata();
                break;
            case R.id.tv_left:
                finish();
                break;
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {

        if (requestCode == 110)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent intent1 = new Intent(this, PhotoPickerActivity.class);
                startActivityForResult(intent1, RequstCode.GETPHOTO);
            } else
            {
                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==RequstCode.GETPHOTO){
                if(data!=null){
                    imgstring = data.getStringExtra(SELECT_RESULTS);
                    AppUtil.showPic("file://"+data.getStringExtra(SELECT_RESULTS),img_main);
                    //imageLoader.displayImage("file://" + imgresult, img_store_one, options);
                }
            }
        }
    }
}
